import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import { Card, Pagination, Form, Row, Col,Avatar,Popover,Modal,Table,Spin,
    Select, Input, InputNumber, DatePicker,Button, Icon, Tabs, List,message,Tooltip
} from 'antd';
import HeaderTab from '@/components/HeaderTab';
import styles from './index.less';
import {abs} from '@/utils/utils';
import ExportOrder from './exportOrder';
import ReportForm from '../orderList/reportForm';
import moment from 'moment';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

const orderStatus = [
    {
        label: '全部',
        value: 0
    },
  {
      label: '待发货',
      value: 2
  },
  {
      label: '已发货',
      value: 3
  },
  {
      label: '退款中',
      value: 4
  },
  {
      label: '已完成',
      value: 5
  },
  {
      label: '已关闭',
      value: 6
  },
]

const rightsStatus = [
    {
       label: '全部',
       value: 90
    },
    {
         label: '退款申请中',
         value: 10
     },
     {
         label: '已退货,待收货',
         value: 30
     },
   ]

@Form.create()
class RefundsList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      btnLoading: false,
      formValues: {},
      Sort: 'Desc',
      serchLoading: false,
      exportLoading: false,
      visible: false,
      formData: {},
      paginationProps: {
        showSizeChanger: true,
        showQuickJumper: false,
        showTotal: total => `共 ${total} 条记录`,
        pageSize: 10,
        total: 0,
        pageIndex: 1,
      },
      tabs: [{
        title: '全部',
        key: `/${window.storeId}/order/refunds`,
      }, {
        title: '待商家处理',
        key:  `/${window.storeId}/order/refunds/waitseller`
      },{
        title: '待买家处理',
        key:  `/${window.storeId}/order/refunds/waitbuyer`
      }]
    };
  }


  componentWillMount(){
    this.getList();
    window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
  }

  onChange = (data)=> {
    this.setState({
      current: data.current,
      pageSize: data.pageSize,
    });
  }


  onTabChange=(id)=> {
    this.setState({
      activeId: id
    },()=>{
        router.replace({
            pathname: `${id}`
        })
    });
  }

  // 点击单个分页
    onChangeOnePage = (current, pageSize) => {
        let { paginationProps, formValues} = this.state;
        let pagination = {
          ...paginationProps,
          pageIndex: current,
          pageSize: pageSize
        };
        this.setState({
          paginationProps: pagination,
          serchLoading: true
        }, () => {
          this.getList({...formValues});
        })
    }

     // 改变显示长度
  onShowSizeChange =(current, pageSize) => {
    let { paginationProps,formValues} = this.state;
    let pagination = {
      ...paginationProps,
      pageIndex: current,
      pageSize: pageSize
    };
    this.setState({
      paginationProps: pagination,
      serchLoading: true
    }, () => {
      this.getList({...formValues});
    })
  }



  getList = params => {
    const { dispatch} = this.props;
    const { paginationProps: { pageIndex, pageSize }, Sort } = this.state;
    dispatch({
        type: 'orderRight/GetList',
        payload: {
            PageIndex: pageIndex, //页码
            PageSize: pageSize, //页数
            OrderNo:params && params.OrderNo ? params.OrderNo : '', //订单号
            ProductWord: params && params.ProductWord ? params.ProductWord : '', //商品
            RefundOrderNo: params && params.RefundOrderNo ? params.RefundOrderNo : '', //维权单
            MinDate: params && params.MinDate? params.MinDate: null,
            MaxDate: params && params.MaxDate? params.MaxDate: null,
            RightsStatus: params && params.RightsStatus? params.RightsStatus: 90, //维权状态
            RefundType: params && params.RefundType? params.RefundType: 0, //	配送方式
            OrderStatus: params && params.OrderStatus? params.OrderStatus: 0, //订单状态
            Sort: Sort
        },
        callBack: {
            success: res => {
                if(res.Code ===0) {
                  this.setState({
                    paginationProps: {
                        ...this.state.paginationProps,
                        total: res.Data.Total
                    },
                    dataSource: res.Data,
                    loading: false,
                    // loadFinished: true,
                    btnLoading: false,
                    serchLoading: false,
                  })
                }
            },
            error: res => {
                console.log(res)
            }
        }
    })
  }

    // 筛选
    handleSearch = e => {
        e.preventDefault();
        this.setState({
            btnLoading: true,
            serchLoading: true
        })
        const { form } = this.props;
        form.validateFields((err, values) => {
            if(err) return;
            const datas = {
                ...values,
                MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
                MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
            };
            this.setState({
                formValues: datas,
            })
           this.getList({...datas});
        })
   }

   onTableChange =(pagination, filters, sorter) => {
       const {formData,formValues} = this.state;
       if(sorter.order ==='descend') {
            formData.Sort ='Desc';
            this.setState({
                Sort: 'Desc'
            })
       } else {
        formData.Sort ='Asc';
        this.setState({
            Sort: 'Asc'
        })
       }
        this.setState({
            formData,
            serchLoading: true
        })
        this.getList({...formValues});
   }

// 重置
  handleFormReset =() => {
    const { form } = this.props;
    form.resetFields();
  }

  //导出
  clickexportOrder =() => {
    const { dispatch, form} = this.props;
    const {Sort} = this.state;
    form.validateFields((err, values) => {
        if(values.Date) {
            const datas = {
                ...values,
                MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
                MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
                Sort:Sort
            };
            this.setState({
                formData: datas,
                exportLoading: true,
            })
            dispatch({
                type: 'orderList/GetTaskName',
                payload: {
                    TaskType: 4
                },
                callBack: {
                    success: res => {
                        if(res.Code===0) {
                            this.setState({
                                data: res.Data,
                                visible: true,
                                exportLoading: false
                            })
                        }
                    },
                    error: res=> {
                        message.error(res.Msg)
                    }
                }
            })
        } else {
            message.error('请选择起始时间')
        }
    })

  }

  // 报表
  clickReportForm =() => {
    const title="已生成报表";
    const TaskType = 4; //类型
    const width = 640;
    this.reportForm.show({width, title, TaskType})
  }

  clickDetail =(Id)=> {
    window.open(`/#/${window.storeId}/order/refunds/details/${Id}`);
  }

  renderForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    const {btnLoading, exportLoading} = this.state;
    return (
        <Form onSubmit={this.handleSearch} layout="inline" className={styles.formItems}>
        <Row>
          <Col span={8}>
            <FormItem label="订单编号">
              {getFieldDecorator('OrderNo')(
                <Input style={{ width: '100%' }}/>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="商品名称">
              {getFieldDecorator('ProductWord')(
                <Input style={{ width: '100%' }}/>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="退款状态">
                {getFieldDecorator('RightsStatus', {initialValue: 90})(
                    <Select placeholder="请选择" className="xkd-width-per-100">
                           {rightsStatus.map((item, index) => (
                            <Option value={item.value} key={index}>{item.label}</Option>
                        ))}
                    </Select>
                    )}
            </FormItem>
          </Col>
       
        </Row>
        <Row>
            <Col span={8}>
                <FormItem label="维权单号">
                {getFieldDecorator('RefundOrderNo')(
                    <Input style={{ width: '100%' }}/>
                )}
                </FormItem>
            </Col>
            <Col span={8}>
                <FormItem label="订单状态">
                {getFieldDecorator('OrderStatus',{initialValue: 0})(
                    <Select placeholder="请选择" style={{ width: '100%' }}>
                        {orderStatus.map((item, index) => (
                            <Option value={item.value} key={index}>{item.label}</Option>
                        ))}
                    </Select>
                )}
                </FormItem>
            </Col>
            <Col span={8}>
                <FormItem label="退款方式">
                    {getFieldDecorator('RefundType', {initialValue: 0})(
                        <Select placeholder="请选择" style={{ width: '100%' }}>
                            <Option value={0}>全部</Option>
                            <Option value={1}>仅退款</Option>
                            <Option value={2}>退货退款</Option>                        
                        </Select>
                    )}
                </FormItem>
            </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label="申请时间">
              {getFieldDecorator('Date')(<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '    结束日期']} />)}
            </FormItem>
          </Col>
     
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div className="screenNavButton">
                <Button type="primary" htmlType="submit" loading={btnLoading}>
                    筛选
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                    重置
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={()=>this.clickexportOrder()} loading={exportLoading}>
                    订单导出
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.clickReportForm}>
                    查看已生成报表
                </Button>
            </div>
        </div>
      </Form>
    )
  }



  render() {
    const { paginationProps, dataSource,  serchLoading, loading, formData} = this.state;
    const columns =[
        {
          title: '商品',
          dataIndex: 'NickName',
          width:'28.5%'
        },
        {
          title: '发货状态',
          dataIndex: 'Telephone',
          width:'13%',
        },
        {
          title: '订单金额',
          dataIndex: 'LastBuyTime',
          width:'12.5%',
          align: 'right',
        },
        {
          title: '退款金额',
          dataIndex: 'TotalPoints',
          width:'12.5%',
          align: 'right',
        },
        {
          title: '申请时间',
          dataIndex: 'CreateTime',
          width:'12.5%',
          sorter: true,
          defaultSortOrder: 'descend',
        },
        {
          title: '退款状态',
          dataIndex: 'SingleFee',
          width:'12.5%'
        },
        {
          title: '操作',
          align: 'right',
        },
      ];
    return (
        <Fragment>
            {/* <HeaderTab 
                    _this={this}
                    type="slider"
                    activeId={this.state.activeId}
                    onChange={this.onTabChange}
                    tabs={this.state.tabs}
                >         
            </HeaderTab> */}
            <Spin spinning={loading}>
                <Card bordered={false} className={styles.contentBox}>  
                    <div style={{height:206,background:'#fafafa',marginBottom:16,paddingTop:16,paddingRight:16,boxSizing:'border-box'}}>
                        <div className="tableListForm">{this.renderForm()}</div>
                    </div>
                    <div className={styles.bodyContent}>
                        <List
                            header={
                                <Table
                                    dataSource={null}
                                    columns={columns}
                                    onChange={this.onTableChange}
                                />
                            }
                            loading={serchLoading}
                            itemLayout="vertical"
                            size="large"
                            dataSource={dataSource&& dataSource.DataList?dataSource.DataList:[]}
                            renderItem={vel => {
                                return (
                                    <List.Item className={styles.listBody}>
                                        <Row className={styles.navtebalRow}>
                                            <Col span={20} className={styles.orderNo}>
                                                <span>维权单号: {vel.RightsOrderNo}</span>
                                                <span style={{marginLeft: 16, marginRight: 16}}>订单号: {vel.OrderNo}</span>    
                                            </Col>
                                            <Col span={4}>
                                                <div style={{textAlign: 'right', paddingRight: 16}}>
                                                    <span>{'(' +vel.RefundTypeName+ ')'}</span>
                                                </div>
                                            </Col>
                                        </Row>
                                        <Row className={styles.navRowItem} style={{height: `${vel.RightsItem.length * 96}px`}}>
                                            <Col span={10}>
                                                <List
                                                    dataSource={vel.RightsItem ?vel.RightsItem:[]}
                                                    renderItem={(data, index) => {
                                                        return (
                                                            <Row className={vel.RightsItem.length === index+ 1 ?styles.leftItemNoborder : styles.leftItem}>
                                                                <Col span={16}>
                                                                    <List.Item key={data.Id} className={styles.listItem}>
                                                                        <List.Item.Meta
                                                                            title={
                                                                                <span title={data.ProductName} style={{maxWidth:184,height:40}}>
                                                                                    {data.ProductName}
                                                                                </span>
                                                                            }
                                                                            description={
                                                                                <span
                                                                                    title={data.SkuName}
                                                                                    className="xkd-text-ellipsis"
                                                                                >{data.SkuName}</span>
                                                                            }
                                                                        />
                                                                    </List.Item>
                                                                </Col>
                                                                <Col span={8}>{data.RightsSendState}</Col>
                                                            </Row>
                                                        )
                                                    }}
                                                >
                                                </List>
                                            </Col>
                                            <Col span={3}>
                                                <div>{'￥' +abs(vel.TradeFee,2)}</div>
                                            </Col>
                                            <Col span={3}>
                                                <div>{'￥' +abs(vel.RefundFee,2)}</div>
                                            </Col>
                                            <Col span={3}>{vel.CreateTime}</Col>                               
                                            <Col span={3} >{vel.StatusName}</Col>
                                            <Col span={2} >
                                                <Button type="primary" size="small" onClick={()=> this.clickDetail(vel.Id)}>处理退款</Button>
                                            </Col>
                                        </Row>
                                    </List.Item>
                                )
                            }}
                        />                   
                    </div>
 
                    <Pagination
                        showSizeChanger
                        onChange={this.onChangeOnePage}
                        onShowSizeChange={this.onShowSizeChange}
                        showTotal={paginationProps.showTotal}
                        total={paginationProps.total}
                        current={paginationProps.pageIndex}
                        pageSize={paginationProps.pageSize}
                        style={{textAlign: 'right'}}
                    />
                </Card>
            </Spin>
            <ExportOrder _this = {this} visible={this.state.visible} data={formData} TaskType={4}/>
            <ReportForm
                ref={e => {
                    this.reportForm = e;
                }}
            />
        </Fragment>
    );
  }
}


export default connect(({ orderRight,global, loading }) => ({
    orderRight,
    oemInfo: global.oemInfo,
  }))(RefundsList)